package com.learn.security.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 自定义用户认证
 */
@Component
public class MyUserDetailsService implements UserDetailsService,SocialUserDetailsService{

    Logger logger = LoggerFactory.getLogger(getClass());

    // 密码加解密的Encoder
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("账号密码登录用户名：" + username);
        return buildDetails(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        logger.info("社交登录用户名：" + userId);
        return buildDetails(userId);
    }

    private SocialUser buildDetails(String username) {
        // 根据用户名查找用户信息
        // 此处应该为注册过程加密
        String password = passwordEncoder.encode("123456");
        logger.info("数据库密码：" + password);

        // 根据从数据库中查询的信息来校验
        return new SocialUser(username, password,
                true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin")) ;
    }
}
